<template>
  <div class="script-management">
    <div class="page-header">
      <div class="header-left">
        <h3>脚本管理</h3>
        <p>管理基础脚本版本和自动更新</p>
      </div>
      <div class="header-right">
        <el-upload
          :action="uploadUrl"
          :before-upload="beforeUpload"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          :show-file-list="false"
          accept=".js,.py">
          <el-button type="primary">上传脚本</el-button>
        </el-upload>
      </div>
    </div>

    <div class="content">
      <el-card>
        <el-table
          :data="scriptList"
          :loading="loading"
          stripe>

          <el-table-column prop="scriptName" label="脚本名称" width="200" />

          <el-table-column prop="version" label="版本号" width="120" />

          <el-table-column prop="description" label="描述" min-width="200" />

          <el-table-column prop="fileSize" label="文件大小" width="120">
            <template #default="{ row }">
              {{ formatFileSize(row.fileSize) }}
            </template>
          </el-table-column>

          <el-table-column prop="isActive" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'info'">
                {{ row.isActive ? '活跃' : '历史' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createdAt" label="上传时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="!row.isActive"
                type="success"
                size="small"
                @click="activateVersion(row)">
                激活
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="downloadScript(row)">
                下载
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteVersion(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传脚本"
      width="500px">
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="脚本名称" required>
          <el-input v-model="uploadForm.scriptName" placeholder="请输入脚本名称" />
        </el-form-item>
        <el-form-item label="版本号" required>
          <el-input v-model="uploadForm.version" placeholder="如：1.0.0" />
        </el-form-item>
        <el-form-item label="版本描述">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请描述此版本的更新内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpload">确认上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/request'

// 状态管理
const loading = ref(false)
const scriptList = ref([])
const uploadDialogVisible = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 上传表单
const uploadForm = reactive({
  scriptName: '',
  version: '',
  description: ''
})

// 上传URL
const uploadUrl = computed(() => '/api/scripts/upload')

// 初始化
onMounted(() => {
  loadScriptList()
})

// 加载脚本列表
const loadScriptList = async () => {
  loading.value = true
  try {
    const response = await http.get('/scripts', {
      page: pagination.page,
      size: pagination.size
    })

    scriptList.value = response.data.list || []
    pagination.total = response.data.total || 0

  } catch (error) {
    ElMessage.error('加载脚本列表失败')
    console.error('加载脚本列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 上传前处理
const beforeUpload = (file) => {
  const isScript = file.name.endsWith('.js') || file.name.endsWith('.py')
  if (!isScript) {
    ElMessage.error('只能上传 .js 或 .py 脚本文件')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('脚本文件大小不能超过 10MB')
    return false
  }

  // 显示上传对话框
  uploadDialogVisible.value = true
  return false // 阻止自动上传
}

// 确认上传
const confirmUpload = () => {
  if (!uploadForm.scriptName || !uploadForm.version) {
    ElMessage.error('请填写脚本名称和版本号')
    return
  }

  uploadDialogVisible.value = false
  // 这里需要手动处理文件上传
  ElMessage.info('文件上传功能需要完善')
}

// 上传成功
const onUploadSuccess = (response) => {
  ElMessage.success('脚本上传成功')
  loadScriptList()
}

// 上传失败
const onUploadError = (error) => {
  ElMessage.error('脚本上传失败')
  console.error('上传失败:', error)
}

// 激活版本
const activateVersion = async (script) => {
  try {
    await ElMessageBox.confirm(`确认激活 ${script.scriptName} v${script.version}？`, '确认操作', {
      type: 'warning'
    })

    await http.put(`/scripts/${script.scriptName}/${script.version}/activate`)
    ElMessage.success('版本激活成功')
    await loadScriptList()

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('激活版本失败')
      console.error('激活版本失败:', error)
    }
  }
}

// 下载脚本
const downloadScript = async (script) => {
  try {
    const response = await fetch(`/api/scripts/${script.scriptName}/${script.version}/download`)
    const blob = await response.blob()

    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${script.scriptName}-${script.version}.js`
    link.click()

    window.URL.revokeObjectURL(url)
    ElMessage.success('脚本下载成功')

  } catch (error) {
    ElMessage.error('下载脚本失败')
    console.error('下载脚本失败:', error)
  }
}

// 删除版本
const deleteVersion = async (script) => {
  try {
    await ElMessageBox.confirm(`确认删除 ${script.scriptName} v${script.version}？`, '确认删除', {
      type: 'danger'
    })

    await http.delete(`/scripts/${script.id}`)
    ElMessage.success('版本删除成功')
    await loadScriptList()

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除版本失败')
      console.error('删除版本失败:', error)
    }
  }
}

// 分页处理
const handleSizeChange = () => {
  pagination.page = 1
  loadScriptList()
}

const handleCurrentChange = () => {
  loadScriptList()
}

// 工具方法
const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = size

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }

  return `${fileSize.toFixed(1)} ${units[index]}`
}

const formatDateTime = (dateTime) => {
  return dateTime ? new Date(dateTime).toLocaleString() : '-'
}
</script>

<style lang="scss" scoped>
.script-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    text-align: center;
  }
}
</style>